package com.grm.distributed.lock.service;

import com.grm.distributed.lock.common.Result;
import com.grm.distributed.lock.mapper.ProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * redis基于setnx指令实现分布式锁-递归调用
 */
@Slf4j
@Service
public class ProductService6 {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public Result sell() {
        // 1. 执行setnx加锁,setIfPresent：存在就设置，setIfAbsent：不存在就设置(setnx)
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent("lock","111");
        // 2. 获取锁失败，重试:递归调用
        if(Boolean.FALSE.equals(flag)){
            try {
                Thread.sleep(50);
                log.info("递归调用重试获取锁中");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            sell();
        }else {
            try{
                // 2. 查库存
                String productCountStr = stringRedisTemplate.opsForValue().get("product_count");
                Integer count = Integer.valueOf(productCountStr);
                // 3. 扣减库存
                if(count > 0){
                    count = count - 1;
                }
                log.info("product current count = {}",count);
                stringRedisTemplate.opsForValue().set("product_count",String.valueOf(count));
            }finally {
                // 4. 解锁
                stringRedisTemplate.delete("lock");
            }
        }
        return Result.success();
    }
}
